﻿using System;
using System.Net;
using Microsoft.Win32;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;
using System.Drawing;

namespace DVDFilmoteka.Settings
{
    public class SettingsManager
    {
        private static readonly SettingsManager instance = new SettingsManager();
        
        public DataClass Data = new DataClass();
        public class DataClass
        {
            public DataClass()
            {
                AutomaticUpdate = true;
                UseProxy = false;
                UseDefaultProxy = true;
                ProxyIPAddress = null;
                ProxyPort = 0;
                ViewResults = true;
                DontChangeNames = false;
                DontChangeGenres = false;
                LoadPicturesOnline = true;
                BetaInform = true;
                LastWindowPosition = new Rectangle(100, 100, 650, 600);
                LastLoadedFile = String.Empty;
                Language = "cs-CZ";
            }

            public Boolean AutomaticUpdate { get; set; }
            public Boolean UseProxy { get; set; }
            public Boolean UseDefaultProxy { get; set; }            
            public String ProxyIPAddress{ get; set; }
            public Int32 ProxyPort { get; set; }
            public Boolean ViewResults { get; set; }
            public Boolean DontChangeNames { get; set; }
            public Boolean DontChangeGenres { get; set; }
            public Boolean LoadPicturesOnline { get; set; }
            public Boolean BetaInform { get; set; }
            public Rectangle LastWindowPosition { get; set; }
            public String LastLoadedFile { get; set; }
            public String Language { get; set; }
        }

        private readonly String FileName;

        #region Jiz nepouzivane klice z registru - kompatibilita s predchozymi verzemi
        private const String automaticUpdateKey = "autoUpdate";        
        private const String useProxyKey = "useProxy";        
        private const String useDefaultProxyKey = "useDefaultProxy";        
        private const String proxyIPAddressKey = "proxyIP";        
        private const String proxyPortKey = "proxyPort";        
        private const String viewResultsKey = "viewResults";        
        private const String dontChangeNames = "dontChangeNames";        
        private const String dontChangeGenres = "dontChangeGenres";        
        private const String loadPicturesOnline = "loadPicturesOnline";        
        private const String betaInform = "betaInform";
        #endregion

        /// <summary>
        /// Konstruktor
        /// </summary>
        private SettingsManager()
        {
            // Urcit umisteni souboru, pripadne vytvorit adresar
            try
            {
                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DVD Filmotéka"))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DVD Filmotéka");
                }

                FileName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\DVD Filmotéka\\Settings.xml";
            }
            catch (Exception) { }

            try
            {
                Boolean b = LoadFromRegistery(); // Nacist z registru (ukladaly to tam starsi verze)
                if (b)
                {
                    if (SaveToFile()) // Ulozit do souboru a vymazat vsechno z registru
                    {
                        try
                        {
                            Registry.CurrentUser.DeleteSubKeyTree("Software\\MJ Design\\DVD Filmoteka");
                        }
                        catch (Exception) { }

                        try
                        {
                            Registry.LocalMachine.DeleteSubKeyTree("Software\\MJ Design\\DVD Filmoteka");
                        }
                        catch (Exception) { }
                    }
                }
                else
                {
                    LoadFromFile();
                }
            } catch (Exception) { }
        }

        /// <summary>
        /// Tovarni metoda
        /// </summary>
        /// <returns></returns>
        public static SettingsManager Instance
        {
            get
            {
                return instance;
            }
        }

        /// <summary>
        /// Nacte nastaveni z registru
        /// </summary>
        public Boolean LoadFromRegistery()
        {
            RegistryKey regKeyAppRoot = Registry.CurrentUser.OpenSubKey("Software\\MJ Design\\DVD Filmoteka");
            if (regKeyAppRoot == null)
            {
                regKeyAppRoot = Registry.LocalMachine.OpenSubKey("Software\\MJ Design\\DVD Filmoteka");
                if (regKeyAppRoot == null) return false;
            }

            Data.AutomaticUpdate = "true".Equals((string)regKeyAppRoot.GetValue(automaticUpdateKey, "true"));
            Data.UseProxy = "true".Equals((string)regKeyAppRoot.GetValue(useProxyKey, "false"));
            Data.UseDefaultProxy = "true".Equals((string)regKeyAppRoot.GetValue(useDefaultProxyKey, "true"));
            Data.ViewResults = "true".Equals((string)regKeyAppRoot.GetValue(viewResultsKey, "true"));
            Data.DontChangeNames = "true".Equals((string)regKeyAppRoot.GetValue(dontChangeNames, "false"));
            Data.DontChangeGenres = "true".Equals((string)regKeyAppRoot.GetValue(dontChangeGenres, "false"));
            Data.LoadPicturesOnline = "true".Equals((string)regKeyAppRoot.GetValue(loadPicturesOnline, "true"));
            Data.BetaInform = "true".Equals((string)regKeyAppRoot.GetValue(betaInform, "true"));

            // Adresa proxy serveru
            String value = (string) regKeyAppRoot.GetValue(proxyIPAddressKey, "");
            IPAddress address;
            Boolean b = IPAddress.TryParse(value, out address);
            if (b) Data.ProxyIPAddress = address.ToString();

            // Port proxy serveru
            value = (string)regKeyAppRoot.GetValue(proxyPortKey, "");
            Int32 result;
            b = Int32.TryParse(value, out result);
            if (b) Data.ProxyPort = result;

            return true;
        }

        /// <summary>
        /// Nacte nastaveni z XML souboru
        /// </summary>
        public void LoadFromFile()
        {
            StreamReader s = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(Data.GetType());
                s = new StreamReader(FileName);
                object o = serializer.Deserialize(s);
                if (o != null && o is DataClass)
                {
                    Data = o as DataClass;
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (s != null) s.Close();
            }
        }

        /// <summary>
        /// Ulozi nastaveni do souboru
        /// </summary>
        public Boolean SaveToFile()
        {
            StreamWriter s = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(Data.GetType());
                s = new StreamWriter(FileName);
                serializer.Serialize(s, Data);
                if (s != null)
                {
                    s.Flush();
                    s.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                if (s != null)
                {
                    s.Flush();
                    s.Close();
                }

                return false;
            }            
        }

        /// <summary>
        /// Ulozi nastaveni do registru
        /// </summary>
        /*public void saveToRegister()
        {
            RegistryKey regKeyAppRoot = Registry.CurrentUser.CreateSubKey("Software\\MJ Design\\DVD Filmoteka");
            if (regKeyAppRoot == null) return;

            // Automaticky update
            if (AutomaticUpdate)
            {
                regKeyAppRoot.SetValue(automaticUpdateKey, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(automaticUpdateKey, "false");
            }

            // Vysledky hledani
            if (ViewResults)
            {
                regKeyAppRoot.SetValue(viewResultsKey, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(viewResultsKey, "false");
            }

            // Pouzit proxy
            if (UseProxy)
            {
                regKeyAppRoot.SetValue(useProxyKey, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(useProxyKey, "false");
            }

            // Pouzit defaultni proxy
            if (UseDefaultProxy)
            {
                regKeyAppRoot.SetValue(useDefaultProxyKey, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(useDefaultProxyKey, "false");
            }

            // Adresa proxy serveru
            if (ProxyIPAddress == null)
            {
                regKeyAppRoot.SetValue(proxyIPAddressKey, "");
            }
            else
            {
                regKeyAppRoot.SetValue(proxyIPAddressKey, ProxyIPAddress.ToString());
            }

            // Nemenit nazvy filmu
            if (DontChangeNames)
            {
                regKeyAppRoot.SetValue(dontChangeNames, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(dontChangeNames, "false");
            }

            // Nemenit zanry filmu
            if (DontChangeGenres)
            {
                regKeyAppRoot.SetValue(dontChangeGenres, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(dontChangeGenres, "false");
            }

            // Nacitat obrazky online
            if (LoadPicturesOnline)
            {
                regKeyAppRoot.SetValue(loadPicturesOnline, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(loadPicturesOnline, "false");
            }

            // Upozornovat na betaverze
            if (BetaInform)
            {
                regKeyAppRoot.SetValue(betaInform, "true");
            }
            else
            {
                regKeyAppRoot.SetValue(betaInform, "false");
            }

            // Port proxy serveru
            regKeyAppRoot.SetValue(proxyPortKey, ProxyPort.ToString());
        }*/
    }
}